import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest, HttpHeaders, HttpParams, HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { from, Observable, of, Subject, BehaviorSubject, observable } from 'rxjs';
import { ApiResponse } from '@/app/core/model/api.response';
import { WebSocketUtil } from './websocket';
import { filter } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class RequestService {

  constructor(private http: HttpClient, private webSocketUtil: WebSocketUtil) { }

  /**
   * get方法
   * @param url 
   * @param options 
   * @param params 
   */
  public get(url: string, httpOptions: Object, params?: any): Observable<ApiResponse> {
    let httpParams = new HttpParams();
    if (params) {
      for (const key in params) {
        if (params[key] === false || params[key]) {
          httpParams = httpParams.set(key, params[key]);
        }
      }
    }
    httpOptions['params'] = httpParams;
    return this.http.get<ApiResponse>(url, httpOptions);
  }

  /**
   * post方法
   * @param url 
   * @param body 
   */
  public post(url: string, httpOptions: Object, params: any, type?: string): Observable<ApiResponse> {
    return this.http.post<ApiResponse>(url, params, httpOptions);
  }

  /**
 *删除方法
 * @param url 
 * @param body 
 */
  public delete(url: string, httpOptions: Object, type?: string): Observable<any> {
    return this.http.delete<ApiResponse>(url, httpOptions);
  }

  /**
 * 上传方法
 * @param url 
 * @param body 
 */
  public upload(url: string, httpOptions: Object, params: any) {
    const req = new HttpRequest('POST', url, params, httpOptions);
    return this.http.request(req).pipe(filter(e => e instanceof HttpResponse));
  }

  /**
 * websocket连接方式
 * @param url 
 * @param params 
 */
  public websocket(url: string) {
    return this.webSocketUtil.getWebsocket(url);
  }

  /**
  * 处理请求失败的错误
  * @param error HttpErrorResponse
  */
  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return error.error;
  }

}
